package org.coc.betterchicago.rest;

import java.io.IOException;

import org.coc.betterchicago.BetterChicagoAuth;
import org.coc.betterchicago.TwitterOAuth;
import org.coc.betterchicago.beans.BetterChicagoUser;
import org.coc.betterchicago.beans.DAO;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;

/**
 * @author manu
 *         Check cookie value, if doesn't exist send back an error with login url
 *         If cookie exist, get the user accesstoken from database & authenticate the user
 *         If "verifyCredentials fail", send back an error with login url
 */
public class UserInfoResource extends ServerResource {

	@Get("json")
	public String handleGet() {
		try {
			return handleJson().getText();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public JsonRepresentation handleJson() {
		String userId = (String) getRequest().getAttributes().get("id");
		TwitterOAuth oauth = new TwitterOAuth();
		User twitterUser = oauth.authorize(Long.valueOf(userId));
		if (twitterUser != null) {
			try {
				JSONObject json = new JSONObject();
				json.put("name", twitterUser.getName());
				json.put("screen", twitterUser.getScreenName());
				json.put("picture", twitterUser.getProfileImageURL());
				JsonRepresentation jsonRep = new JsonRepresentation(json);
				return jsonRep;
			} catch (Exception e) {
				e.printStackTrace();
				return error();
			}
		} else {
			return error();
		}
	}

	private JsonRepresentation error() {
		JSONObject json = new JSONObject();
		try {
			json.put("error", "User requires authentication.");
		} catch (JSONException e) {
			return new JsonRepresentation("{\"error\": \"User requires authentication.\"}");
		}
		JsonRepresentation jsonRep = new JsonRepresentation(json);
		return jsonRep;
	}

	public JsonRepresentation handleJsonOld() {
		try {
			String userId = (String) getRequest().getAttributes().get("id");
			// Series<Cookie> cookies = getCookies();
			// cookies.getFirstValue("bc_id");

			if (userId != null) {
				long id = Long.valueOf(userId).longValue();
				DAO dao = new DAO();
				BetterChicagoUser user = dao.getBetterChicagoUser(id);
				if (user != null) {
					Twitter twitter = new TwitterFactory(BetterChicagoAuth.CONFIGURATION).getInstance();
					twitter.setOAuthAccessToken(new AccessToken(user.getToken(), user.getTokenSecret()));
					try {
						User twitterUser = twitter.verifyCredentials();
						JSONObject json = new JSONObject();
						json.put("name", twitterUser.getName());
						json.put("screen", twitterUser.getScreenName());
						json.put("picture", twitterUser.getProfileImageURL());
						JsonRepresentation jsonRep = new JsonRepresentation(json);
						return jsonRep;
					} catch (TwitterException e) {
						e.printStackTrace();
						return error();
					}
				}
			}
			return error();
		} catch (Exception e) {
			e.printStackTrace();
			return error();
		}
	}

}
